
document.addEventListener('DOMContentLoaded', function() {
    const messageList = document.getElementById('messageList');
    const actionModal = document.getElementById('actionModal');
    const filterBtns = document.querySelectorAll('.filter-btn');
    let messages = JSON.parse(localStorage.getItem('messages')) || [];
    let currentMessageId = null;

    // 初始化消息数据
    if (messages.length === 0) {
        messages = generateSampleMessages();
        saveMessages();
    }

    // 渲染消息列表
    function renderMessages(filter = 'all') {
        messageList.innerHTML = '';
        
        let filteredMessages = messages;
        if (filter === 'unread') {
            filteredMessages = messages.filter(msg => !msg.read);
        } else if (filter === 'read') {
            filteredMessages = messages.filter(msg => msg.read);
        }

        if (filteredMessages.length === 0) {
            messageList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>没有找到消息</p>
                </div>
            `;
            return;
        }

        filteredMessages.forEach(message => {
            const messageItem = document.createElement('div');
            messageItem.className = `message-item ${message.read ? '' : 'unread'}`;
            messageItem.dataset.id = message.id;
            
            messageItem.innerHTML = `
                <div class="message-icon">
                    <i class="${getMessageIcon(message.type)}"></i>
                </div>
                <div class="message-content">
                    <div class="message-title">
                        <span>${message.title}</span>
                        <span class="message-time">${formatTime(message.time)}</span>
                    </div>
                    <p class="message-text">${message.content}</p>
                    <div class="message-actions">
                        <button class="action-btn mark-btn">
                            <i class="fas fa-${message.read ? 'envelope' : 'envelope-open'}"></i>
                            ${message.read ? '标记未读' : '标记已读'}
                        </button>
                        <button class="action-btn delete-btn">
                            <i class="fas fa-trash-alt"></i>
                            删除
                        </button>
                    </div>
                </div>
            `;
            
            messageList.appendChild(messageItem);
        });

        // 添加事件监听
        document.querySelectorAll('.mark-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const messageId = this.closest('.message-item').dataset.id;
                toggleReadStatus(messageId);
            });
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const messageId = this.closest('.message-item').dataset.id;
                showActionModal(messageId);
            });
        });

        document.querySelectorAll('.message-item').forEach(item => {
            item.addEventListener('click', function() {
                const messageId = this.dataset.id;
                showActionModal(messageId);
            });
        });
    }

    // 显示操作模态框
    function showActionModal(messageId) {
        currentMessageId = messageId;
        const message = messages.find(msg => msg.id === messageId);
        
        actionModal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    // 关闭操作模态框
    function closeActionModal() {
        actionModal.classList.remove('active');
        document.body.style.overflow = '';
    }

    // 切换已读/未读状态
    function toggleReadStatus(messageId) {
        const messageIndex = messages.findIndex(msg => msg.id === messageId);
        if (messageIndex !== -1) {
            messages[messageIndex].read = !messages[messageIndex].read;
            saveMessages();
            const currentFilter = document.querySelector('.filter-btn.active').dataset.filter;
            renderMessages(currentFilter);
        }
    }

    // 删除消息
    function deleteMessage(messageId) {
        messages = messages.filter(msg => msg.id !== messageId);
        saveMessages();
        const currentFilter = document.querySelector('.filter-btn.active').dataset.filter;
        renderMessages(currentFilter);
    }

    // 保存消息到本地存储
    function saveMessages() {
        localStorage.setItem('messages', JSON.stringify(messages));
    }

    // 生成示例消息
    function generateSampleMessages() {
        const types = ['order', 'promotion', 'system', 'activity'];
        const sampleMessages = [];
        
        for (let i = 1; i <= 10; i++) {
            const type = types[Math.floor(Math.random() * types.length)];
            sampleMessages.push({
                id: `msg-${i}`,
                type: type,
                title: getMessageTitle(type, i),
                content: getMessageContent(type),
                time: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)),
                read: Math.random() > 0.5
            });
        }
        
        return sampleMessages;
    }

    // 获取消息图标
    function getMessageIcon(type) {
        const icons = {
            'order': 'fa-shopping-bag',
            'promotion': 'fa-percentage',
            'system': 'fa-cog',
            'activity': 'fa-gift'
        };
        return icons[type] || 'fa-bell';
    }

    // 获取消息标题
    function getMessageTitle(type, index) {
        const titles = {
            'order': ['订单发货通知', '订单支付成功', '订单已完成'],
            'promotion': ['限时特惠', '会员专享折扣', '新品上市'],
            'system': ['系统维护通知', '账户安全提醒', '新版本更新'],
            'activity': ['周年庆活动', '邀请有礼', '节日特惠']
        };
        const typeTitles = titles[type];
        return typeTitles[Math.floor(Math.random() * typeTitles.length)];
    }

    // 获取消息内容
    function getMessageContent(type) {
        const contents = {
            'order': '您的订单已发货，预计3-5个工作日送达。点击查看物流详情。',
            'promotion': '会员专享8折优惠，活动仅限今日，快来选购吧！',
            'system': '系统将于今晚23:00-24:00进行维护升级，期间可能无法正常访问。',
            'activity': '参与邀请好友活动，最高可获得100元优惠券，立即参与！'
        };
        return contents[type] || '您有一条新消息，请点击查看详情。';
    }

    // 格式化时间
    function formatTime(date) {
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60 * 1000) {
            return '刚刚';
        } else if (diff < 60 * 60 * 1000) {
            return `${Math.floor(diff / (60 * 1000))}分钟前`;
        } else if (diff < 24 * 60 * 60 * 1000) {
            return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
        } else {
            return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
        }
    }

    // 事件监听
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            renderMessages(this.dataset.filter);
        });
    });

    document.querySelector('.modal-close').addEventListener('click', closeActionModal);
    document.querySelector('.mark-read').addEventListener('click', function() {
        toggleReadStatus(currentMessageId);
        closeActionModal();
    });
    document.querySelector('.mark-unread').addEventListener('click', function() {
        toggleReadStatus(currentMessageId);
        closeActionModal();
    });
    document.querySelector('.delete').addEventListener('click', function() {
        deleteMessage(currentMessageId);
        closeActionModal();
    });

    // 初始渲染
    renderMessages();
});
